package org.xxpay.task.reconciliation.scheduled;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.core.entity.PayOrderExample;
import org.xxpay.task.common.service.CommonService;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 处理过期订单- 定时任务
 */
@Component
public class ExpirePayOrderScheduled {

    private static final MyLog logger = MyLog.getLog(ExpirePayOrderScheduled.class);

    @Autowired
    private CommonService commonService;

    @Async
    @Scheduled(cron="0 0/1 * * * ?") // 每1分钟执行一次
    public void updateOrder() {

        //查询所有超时订单
        PayOrderExample condition = new PayOrderExample();
        condition.createCriteria().andExpireTimeLessThan(new Date())
                .andStatusIn(Arrays.asList(PayConstant.PAY_STATUS_INIT, PayConstant.PAY_STATUS_PAYING));

        logger.info("### 开始更新过期订单,每批500条 ###");
        int pageIndex = 1;
        int limit = 500;
        boolean flag = true;
        int allUpdateRow = 0;
        while (flag) {
            // 分页查询, 避免数据过段导致内存溢出
            condition.setOffset((pageIndex - 1) * limit);
            condition.setLimit(limit);

            List<PayOrder> payOrders = commonService.payOrderService.selectByExample(condition);
            for(PayOrder payOrder : payOrders){
                try {
                    int updateRow = commonService.payOrderService.updateOrderClosed(payOrder);
                    allUpdateRow += updateRow;
                } catch (Exception e) {
                    logger.error("订单："+payOrder.getPayOrderId()+",关闭失败", e);
                }
            }
            logger.info("第{}批更新完毕, 更新{}条. ", pageIndex, payOrders.size());
            pageIndex++;
            if(CollectionUtils.isEmpty(payOrders) || payOrders.size() < limit) {
                flag = false;
            }
        }
        logger.info("处理过期订单完成, 共更新{}条. ", allUpdateRow);
    }
}
